package im.yangqiang.android.unicorn.retrofit.interceptor;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 缓存拦截器
 * Created by Carlton on 2016/6/14.
 */
public class HttpCacheInterceptor implements Interceptor
{
    private Context mContext;
    /**
     * 默认缓存4周
     */
    private int mCacheTime = 60 * 60 * 24 * 28;

    public HttpCacheInterceptor(Context context)
    {
        this(context, 0);
    }

    public HttpCacheInterceptor(Context context, int cacheTime)
    {
        mContext = context;
        mCacheTime = cacheTime;
    }

    @Override
    public Response intercept(Chain chain) throws IOException
    {
        Request request = chain.request();
        if ("POST".equals(request.method()))
        {
            return chain.proceed(request);
        } else if ("GET".equals(request.method()))
        {
            if (!isConnected())
            {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }
            Response originalResponse = chain.proceed(request);
            if (isConnected())
            {
                int cacheTime = 0;
                try
                {
                    String time = request.header("cacheTime");
                    cacheTime = TextUtils.isEmpty(time) ? 0 : Integer.parseInt(time);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
                return originalResponse.newBuilder().header("Cache-Control", "public, max-age=" + cacheTime).build();
            } else
            {
                int maxStale = mCacheTime;
                return originalResponse.newBuilder().removeHeader("Pragma").header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).build();
            }
        } else
        {
            return chain.proceed(request);
        }
    }

    /**
     * 是否有网络连接
     *
     * @return
     */
    private boolean isConnected()
    {
        ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

}
